package com.baitengsoft.patentservicemonitor.job.task;

import com.baitengsoft.patentservicemonitor.job.entity.ScheduleJobEntity;
import com.baitengsoft.patentservicemonitor.job.service.ScheduleJobService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.builder.ToStringBuilder;

import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * 测试定时任务(演示Demo，可删除)
 * 
 * testTask为spring bean的名称
 * 
 * @author KennyGu
 * @email 89335272@qq.com
 * @date 2016年11月30日 下午1:34:24
 */
@Component("testTask")
public class TestTask {
	private Logger logger = LoggerFactory.getLogger(getClass());
	static String encoding;
	@Autowired
	private ScheduleJobService scheduleJobService;
	
	public void test(String params){
		logger.info("我是带参数的test方法，正在被执行，参数为：" + params);
		
		try {
			Thread.sleep(1000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		String method = "POST";
		String stringurl = "http://open.patexplorer.com/router";
		// String stringurl = "http://121.43.184.196:8080/router";
		byte[] key = ("ADMIN:KYLIN").getBytes();
		encoding = Base64.encodeBase64String(key);

		System.out.println(excute(stringurl, method, null).toString());

	}
	
	
	public void test2(){
		logger.info("我是不带参数的test2方法，正在被执行");
	}


	/**
	 * 通过httpClient方式调用kylin Restful接口
	 *
	 * @param method
	 * @param params
	 * @return
	 */
	public StringBuffer excute(String stringurl, String method, String params) {
		StringBuffer out = new StringBuffer();
		try {
			URL url = new URL(stringurl);
			System.out.println(url);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod(method);
			connection.setDoOutput(true);
			connection.setRequestProperty("Authorization", "Basic " + encoding);
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			if (params != null) {
				byte[] outputInBytes = params.getBytes("UTF-8");
				OutputStream os = connection.getOutputStream();
				os.write(outputInBytes);
				os.close();
			}
			InputStream content = (InputStream) connection.getInputStream();
			// 解决乱码问题
			BufferedReader in = new BufferedReader(new InputStreamReader(content, Charset.forName("UTF-8")));
			String line;
			while ((line = in.readLine()) != null) {
				out.append(line);
			}
			in.close();
			connection.disconnect();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return out;
	}
}
